package com.dd.service;


import com.dd.model.ConnectionInfo;

import java.sql.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class JdbcConnectionFactory {
    public static final Map<String, ConnectionInfo> CONNECTION_MAP = new ConcurrentHashMap<>();

    public static ConnectionInfo sourceConnectionInfo = null;
    public static ConnectionInfo targetConnectionInfo = null;

    public static Map<String, Connection> sourceConnectionMap = new ConcurrentHashMap<>();
    public static Map<String, Connection> tragetConnectionMap = new ConcurrentHashMap<>();


    /**
     * 测试数据库连接有效性
     *
     * @param info 连接信息
     * @throws ClassNotFoundException 数据库驱动未找到
     * @throws SQLException           连接失败或查询执行失败
     */
    public static void testConnection(ConnectionInfo info) throws ClassNotFoundException, SQLException {
        // 加载数据库驱动（以MySQL为例，其他数据库需调整驱动类名）
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 尝试建立连接并执行简单查询验证
        try (Connection conn = DriverManager.getConnection(info.getUrl(), info.getUsername(), info.getPassword()); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT 1") // 执行最小查询验证连接
        ) {
            // 若能执行到此处，说明连接成功
            if (rs.next()) {
                int result = rs.getInt(1);
                if (result != 1) {
                    throw new SQLException("测试查询返回异常结果");
                }
            }
        }
    }

    public static Connection getSourceConnection(String dbName) throws SQLException {
        String username = sourceConnectionInfo.getUsername();
        String password = sourceConnectionInfo.getPassword();
        String url = sourceConnectionInfo.getUrl();
        Connection connection = sourceConnectionMap.get(dbName);
        if (connection == null) {
            connection = DriverManager.getConnection(url + dbName, username, password);
            sourceConnectionMap.put(dbName, connection);
        }
        return connection;
    }

    public static Connection getTargetConnection(String dbName) throws SQLException {
        String username = targetConnectionInfo.getUsername();
        String password = targetConnectionInfo.getPassword();
        String url = targetConnectionInfo.getUrl();
        Connection connection = tragetConnectionMap.get(dbName);
        if (connection == null) {
            connection = DriverManager.getConnection(url + dbName, username, password);
            tragetConnectionMap.put(dbName, connection);
        }
        return connection;
    }
}
